package com.answerz.module_reportissues.fragment

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.PopupWindow
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.annimon.stream.Collectors
import com.annimon.stream.Stream
import com.answerz.module_reportissues.BR
import com.answerz.module_reportissues.R
import com.answerz.module_reportissues.databinding.FragmentReportSubmitBinding
import com.answerz.module_reportissues.view.FullyGridLayoutManager
import com.answerz.module_reportissues.viewmodel.ReportSubmitViewmodel
import com.czl.base.base.BaseFragment
import com.czl.base.config.AppConstants
import com.czl.base.util.DialogHelper
import com.czl.base.util.GlideEngine
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.SelectorStyles
import com.luck.picture.lib.adapter.GridImageAdapter
import com.luck.picture.lib.broadcast.BroadcastAction
import com.luck.picture.lib.broadcast.BroadcastManager
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.PictureSelectionConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnItemClickListener
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.luck.picture.lib.style.PictureSelectorUIStyle
import com.luck.picture.lib.tools.ToastUtils
import java.io.File
import java.util.*
import kotlin.collections.ArrayList

@Route(path = AppConstants.Router.Report.F_REPORT_SUBMIT)
class ReportSubmitFragment : BaseFragment<FragmentReportSubmitBinding,ReportSubmitViewmodel>() {
    private val maxSelectNum = 4
    private val selectList: ArrayList<LocalMedia> = ArrayList()
    private var gAdapter: GridImageAdapter? = null
    private val pop: PopupWindow? = null
    override fun initContentView(): Int {
        return R.layout.fragment_report_submit
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }

    override fun initData() {
        viewModel.tvTitle.set("报事报修")
        viewModel.reportContentNum.set("1/500")
        // 注册广播
        BroadcastManager.getInstance(context).registerReceiver(
            broadcastReceiver,
            BroadcastAction.ACTION_DELETE_PREVIEW_POSITION,"com.answerz.module_reportissues.fragment.ReportSubmitFragment.uploadImg"
        )
    }
    override fun initViewObservable() {
        viewModel.reportContentNum.set("werlkjaskldf")
        gAdapter= GridImageAdapter(context) {
            showpop()
        }.apply {
            setList(selectList)
            setSelectMax(4)
            setOnItemClickListener(object : OnItemClickListener {
                override fun onItemClick(v: View?,position: Int ) {
//                    val isw=PermissionChecker.checkSelfPermission(context,
//                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                    if (isw){
                    if (selectList.size > 0) {
                        val media = selectList[position]
                        val pictureType: String = media.mimeType
                        val mediaType: Int = PictureMimeType.getMimeType(pictureType)
                        // 预览图片 可自定长按保存路径
//                        PictureWindowAnimationStyle animationStyle = new PictureWindowAnimationStyle();
//                        animationStyle.activityPreviewEnterAnimation = R.anim.picture_anim_up_in;
//                        animationStyle.activityPreviewExitAnimation = R.anim.picture_anim_down_out;
                        var defaultStyle = SelectorStyles.getDefaultStyle(context)
                        defaultStyle.pictureExternalPreviewGonePreviewDelete=false
                        PictureSelector.create(this@ReportSubmitFragment)
                            .themeStyle(R.style.picture_default_style) // xml设置主题
                            .setPictureStyle(defaultStyle) // 动态自定义相册主题
                            //.setPictureWindowAnimationStyle(animationStyle)// 自定义页面启动动画
                            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) // 设置相册Activity方向，不设置默认使用系统
                            .isNotPreviewDownload(true) // 预览图片长按是否可以下载
                            //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定义播放回调控制，用户可以使用自己的视频播放界面
                            .imageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                            .openExternalPreview(position, selectList)
//                            when (mediaType) {
//                                1 ->                             // 预览图片 可自定长按保存路径
//                                    //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
//                                {PictureSelectionConfig.imageEngine=GlideEngine.createGlideEngine()
//                                    PictureSelector.create(this@ReportSubmitFragment)
//                                        .externalPicturePreview(position, selectList,0)}
//
//                                2 ->                             // 预览视频
//                                    PictureSelector.create(activity)
//                                        .externalPictureVideo(media.path)
//                                3 ->                             // 预览音频
//                                    PictureSelector.create(activity)
//                                        .externalPictureAudio(media.path)
//                            }
                    }
//                    }else{
//
//                    }
                }

            })
            setmOnDeleteItemCLickListener{v,p -> if (isLoading()) {
                showNormalToast("请等待图片上传完成")
                false
            }else{
                true
            }
            }
            setmOnItemRetryClickListener {v,p->
                for (item in selectList){
                    item.imageState= GridImageAdapter.STATE_WAIT_LOADING
                }
                gAdapter?.setList(selectList)
                viewModel.localFiles.set(selectList)
                gAdapter?.notifyDataSetChanged()
                viewModel.uploadImgAndVideo(0, data as java.util.ArrayList<LocalMedia>, requireContext())
            }
        }
        binding.rvReportSubmit.apply {
            layoutManager=FullyGridLayoutManager(context,4, GridLayoutManager.VERTICAL, false)
            adapter=gAdapter
        }
        viewModel.reportTypeData.observe(this,{
            if (it!=null&&!it.isEmpty()){
                DialogHelper.showBottomListDialog(requireContext(), Stream.of(it).map { e -> e.name }.withoutNulls()
                    .collect(Collectors.toList()) as java.util.ArrayList<String>
                ) { position, text ->
                    viewModel.reportTypeId.set(it[position].id)
                    viewModel.reportType.set(text)
                }
            }
        })
        viewModel.reportLocationData.observe(this,{
            if (it!=null&&!it.isEmpty()){
                it.add("户外")
                DialogHelper.showBottomListDialog(requireContext(),it) { position, text ->
                    viewModel.reportLocation.set(text)
                }
            }else{
                var ls=ArrayList<String>()
                ls.add("户外")
                DialogHelper.showBottomListDialog(requireContext(),ls) { position, text ->
                    viewModel.reportLocation.set(text)
                }
            }
        })
        viewModel.submitSuccessEvent.observe(this,{
            activity?.finish()
        })
        viewModel.uploadImgEvent.observe(this,{
//            selectList.clear()
//            selectList.addAll(it.fileList)
            gAdapter?.setList(selectList)
            viewModel.localFiles.set(selectList)
            gAdapter?.notifyDataSetChanged()
//            gAdapter?.notifyItemChanged(it.fromIndex)
        })
    }
    fun isLoading():Boolean{
        for (item in selectList){
            if (item.imageState== GridImageAdapter.STATE_WAIT_LOADING ||item.imageState== GridImageAdapter.STATE_LOADING){
                return true
            }
        }
        return false
    }
    fun showpop(){
        var list=ArrayList<String>()
        list.add("相册")
        list.add("拍照")
        DialogHelper.showBottomListDialog(requireContext(), list) { position, text ->
            when (text){
                "相册" ->
                    PictureSelector.create(activity)
                        .openGallery(PictureMimeType.ofAll())
                        .imageEngine(GlideEngine.createGlideEngine())
                        .videoMaxSecond(15)
                        .isShowOutLengthVideos(true)
                        .isMaxSelectEnabledMask(true)
                        .maxSelectNum(4)
                        .maxVideoSelectNum(4)
                        .imageSpanCount(4)
                        .isWithVideoImage(true)
//                        .isOriginalImageControl(true)
//                        .isDisplayOriginalSize(true)
                        .minimumCompressSize(100)
                        .isCompress(true)
                        .selectionMode(PictureConfig.MULTIPLE)
                        .isCamera(false)
                        .isEditorImage(true)
                        .selectionData(selectList)
                        .forResult(object : OnResultCallbackListener<LocalMedia> {
                            @SuppressLint("NotifyDataSetChanged")
                            override fun onResult(result: MutableList<LocalMedia>?) {
                                if (result!=null&&result.size>0){
                                    for (item in result){
                                        Log.e("LocalMedia",item.toString())
                                    }
                                }
                                selectList.clear()
                                if (result != null) {
                                    selectList.addAll(result)
                                }
                                gAdapter?.setList(selectList)
                                viewModel.localFiles.set(selectList)
                                gAdapter?.notifyDataSetChanged()
                                BroadcastManager.getInstance(context)
                                    .action("com.answerz.module_reportissues.fragment.ReportSubmitFragment.uploadImg")
                                    .broadcast()
                            }

                            override fun onCancel() {
                            }
                        })
                "拍照"->
                    PictureSelector.create(activity)
                        .openCamera(PictureMimeType.ofAll())
                        .recordVideoSecond(15)
                        .minimumCompressSize(100)
                        .isCompress(true)
                        .imageEngine(GlideEngine.createGlideEngine())
                        .isUseCustomCamera(true)
                        .forResult(object : OnResultCallbackListener<LocalMedia> {
                            @SuppressLint("NotifyDataSetChanged")
                            override fun onResult(result: MutableList<LocalMedia>?) {
                                if (selectList.size+ result!!.size <=maxSelectNum){
                                    result.let { selectList.addAll(it) }
                                    gAdapter?.setList(selectList)
                                    viewModel.localFiles.set(selectList)
                                    gAdapter?.notifyDataSetChanged()
//                                    viewModel.startUploadEvent.call()
                                    // 删除通知用户更新

                                    BroadcastManager.getInstance(context)
                                        .action("com.answerz.module_reportissues.fragment.ReportSubmitFragment.uploadImg")
                                        .broadcast()
                                }
                            }

                            override fun onCancel() {
                            }
                        })
            }
        }
    }

    private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (TextUtils.isEmpty(action)) {
                return
            }
            if (BroadcastAction.ACTION_DELETE_PREVIEW_POSITION == action) {
                // 外部预览删除按钮回调
                val extras = intent.extras
                if (extras != null) {
                    val position = extras.getInt(PictureConfig.EXTRA_PREVIEW_DELETE_POSITION)
//                    ToastUtils.s(
//                        getContext(),
//                        "delete image index:$position"
//                    )
                    gAdapter?.remove(position)
                    gAdapter?.notifyItemRemoved(position)
                }
            }else if ("com.answerz.module_reportissues.fragment.ReportSubmitFragment.uploadImg"==action){
                for (item in selectList){
                    item.imageState= GridImageAdapter.STATE_WAIT_LOADING
                }
                gAdapter?.setList(selectList)
                viewModel.localFiles.set(selectList)
                gAdapter?.notifyDataSetChanged()
                viewModel.uploadImgAndVideo(0,selectList,requireContext())
            }
        }
    }

    override fun onDestroy() {
        BroadcastManager.getInstance(context)
            .unregisterReceiver(broadcastReceiver, BroadcastAction.ACTION_DELETE_PREVIEW_POSITION,"com.answerz.module_reportissues.fragment.ReportSubmitFragment.uploadImg")
        super.onDestroy()
    }


}